#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/1/1 21:56
# @Author  : leon yan
# @Site    : 
# @File    : About.py
# @Software: PyCharm

from Cryptodome.Cipher import AES
from PyQt5.QtCore import pyqtSlot, QDate, QFile, QIODevice, QDataStream
from PyQt5.QtWidgets import QDialog, QMessageBox, QApplication

import Globalist as gl
from resource.About_ui import Ui_SettingsDialog


class QAbout(QDialog,Ui_SettingsDialog):
    def __init__(self,parent=None,*args,**kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        if gl.get_value('Company'):
            self.company_le.setText(gl.get_value('Company'))
            self.machine_le.setText(gl.get_value('Machine'))
            # aa3 = QDate.fromString(gl.get_value('AuthorizationDate'), "yyyy年M月d日")
            self.date_le.setText(str(gl.get_value('AuthorizationDate')))
            # print(gl.get_value('SuperUser'), type(gl.get_value('SuperUser')))
        else:
            self.company_le.setText("AuthorizationFileNotFound")
            self.machine_le.setText("AuthorizationFileNotFound")
            self.date_le.setText("AuthorizationFileNotFound")

    def __del__(self):
        print("About is deleted")

    @pyqtSlot()
    def on_btnLogIn_clicked(self):
        uname = self.account_le.text().strip()
        upass = self.psw_le.text().strip()
        # print(uname, upass)
        # print(gl.get_value("SuperAccount"), gl.get_value("SuperPassword"))
        if uname == gl.get_value("SuperAccount") and upass == gl.get_value("SuperPassword"):
            gl.set_value("LoginUser", str(uname))
            gl.set_value("LoginUserName", "超级用户")
            gl.set_value("Admin", 2)
            QMessageBox.information(self, "提示", "登录成功")
            self.close()
        else:
            QMessageBox.warning(self, "警告", "密码或用户名错误，登录失败")

    @pyqtSlot()
    def on_btnLogOut_clicked(self):
        gl.set_value("LoginUser", None)
        gl.set_value("LoginUserName", None)
        gl.set_value("Admin", 0)
        gl.set_value("DevelopMode", 0)
        QMessageBox.information(self, "Tips", "LogOut")
        self.close()

    def _readLicense(self):
        filename = ""
        try:
            filename = r".\Api\license.lic"
            # read json
        except Exception as e:
            QMessageBox.critical(self, "AuthorizationFileNotFound", str(e))

        if filename == "":
            return
        self.__testFileName = filename  # lICENSE用文件

        if self.__iniRead():
            try:
                fsize = self.fileDevice.size()
                self.ciphertext = self.fileStream.readRawData(fsize)
                self.do_decrypt()
            except Exception as e:
                QMessageBox.critical(self, "读String过程出现错误", str(e))
            finally:
                self.__delFileStream()

    def __iniRead(self):  # 开始读文件操作
        if not QFile.exists(self.__testFileName):
            QMessageBox.critical(self, "Error", "AuthorizationFileNotFound")
            self.company_le.setText("AuthorizationFileNotFound")
            self.machine_le.setText("AuthorizationFileNotFound")
            self.date_le.setText("AuthorizationFileNotFound")
            return False
        self.fileDevice = QFile(self.__testFileName)  # 创建文件对象
        if not self.fileDevice.open(QIODevice.ReadOnly):
            del self.fileDevice  # 删除对象
            return False

        self.fileStream = QDataStream(self.fileDevice)
        self.fileStream.setVersion(QDataStream.Qt_5_12)  # 设置版本号，写入和读取的版本号要兼容
        return True

    '''私钥解密'''
    def do_decrypt(self):
        # 解密的话要用key和iv生成新的AES对象
        mydecrypt = AES.new(self.key, AES.MODE_CFB, self.ciphertext[:16])
        # 使用新生成的AES对象，将加密的密文解密
        decrypttext = mydecrypt.decrypt(self.ciphertext[16:])
        self.read2panel(decrypttext)

    def read2panel(self,steam):
        aa = steam.decode()
        aa2 = aa.split('$$$')
        self.company_le.setText(aa2[0])
        self.machine_le.setText(aa2[1])
        aa3 = QDate.fromString(aa2[4], "M-d-yyyy")
        self.date_le.setText(str(aa2[4]))

    def __delFileStream(self):  # 结束写文件操作
        self.fileDevice.close()
        del self.fileStream
        del self.fileDevice


if __name__ == '__main__':
    import sys
    app=QApplication(sys.argv)
    objWindow = QAbout()

    objWindow.show()
    sys.exit(app.exec_())


